/**
 *
 * Copyright (C) 2013 陕西威尔伯乐信息技术有限公司
 *
 * @className:com.wellbole.sms.client.impl.SmsFetcherImpl
 * @description: 短信接收器默认实现
 *
 * @version:v1.0.0
 * @author:李飞
 *
 * Modification History:
 * Date         Author      Version     Description
 * -----------------------------------------------------------------
 * 2013年7月1日      李飞                       v1.0.0        create
 *
 */
package com.wellbole.sms.client.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wellbole.sms.client.SmsClient;
import com.wellbole.sms.client.SmsFetcher;
import com.wellbole.sms.client.Version;
import com.wellbole.sms.client.message.InboundMessage;
import com.wellbole.sms.client.result.SmsFetchResult;

/**
 *
 * 短信接收器默认实现
 * 
 * @author 李飞
 *
 */
public class SmsFetcherImpl extends AbstractOperator implements SmsFetcher {
	/**
	 * 日志
	 */
	private static final Logger logger = LogManager.getLogger(Thread.currentThread().getStackTrace()[2].getClassName());

	static {
		logger.info("SmsEngineClient version:" + Version.VERSION + ",update at:" + Version.LAST_UPDATE_AT);
	}

	/**
	 * 默认构造函数，什么都不做，主要用于Spring集成
	 */
	public SmsFetcherImpl() {
		super("1.0", "sms.receive");
	}

	/**
	 * 构造函数，主要用于编程方式实现的场合
	 * 
	 * @param client
	 *            发送数据客户端接口
	 */
	public SmsFetcherImpl(SmsClient client) {
		super("1.0", "sms.receive", client);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.lh.sms.client.SmsReceiver#receive(java.lang.String)
	 */
	@SuppressWarnings("static-access")
	public SmsFetchResult fetch(String extCode) {
		// 限制每秒最多请求3次
		try {
			Thread.currentThread().sleep(300);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		// 检查扩展码
		if (null == extCode) {
			extCode = "";
		}
		// 构造参数表
		Map<String, String> parameters = new HashMap<String, String>();
		parameters.put("extCode", extCode);

		// 发送请求，执行结果
		String responseStr = client.execute(this.version, this.methodName, parameters);

		// 打印原始值
		logger.debug(responseStr);

		// 根据响应内容构建发送结果
		return createResultFromResponse(responseStr);
	}

	/**
	 * 根据响应内容构建发送结果
	 * 
	 * @param responseStr
	 *            执行结果
	 * @return 上行短信列表
	 */
	private SmsFetchResult createResultFromResponse(String responseStr) {
		// {"resultCode":0,"inboundMessages":[{"msgid":"8bdd761a21e94d39b1438b06d052e467","phone":"18966892375","content":"测试短信","receiveAt":"20130515222933","extCode":""},{"msgid":"fee0f0648fa04761a855cb230123b57f","phone":"18802928296","content":"测试短信","receiveAt":"20130515222851","extCode":""}]}

		SmsFetchResult result = null;
		JSONObject jsonObject = null;
		try {
			jsonObject = JSON.parseObject(responseStr);
		} catch (Exception e) {
			result = SmsFetchResult.createSrrHasError(responseStr);
			return result;
		}
		if (jsonObject.containsKey("code")) {
			result = SmsFetchResult.createSrrHasError(jsonObject.getString("message"));
		} else {
			int resultCode = jsonObject.getInteger("resultCode");
			if (resultCode == 2) {
				result = SmsFetchResult.createSrrNoData();
			} else if (resultCode != 0) {
				result = SmsFetchResult.createSrrHasError(jsonObject.getString("errorMessage"));
			} else {
				JSONArray jsonArray = jsonObject.getJSONArray("inboundMessages");
				int number = jsonArray.size();
				List<InboundMessage> inboundMessageList = new ArrayList<InboundMessage>(number);
				for (int index = 0; index < number; index++) {
					JSONObject obj = jsonArray.getJSONObject(index);
					InboundMessage msg = new InboundMessage(obj.getString("msgid"), obj.getString("phone"),
							obj.getString("content"), strToDate(obj.getString("receiveAt")), obj.getString("extCode"));
					inboundMessageList.add(msg);
				}
				result = SmsFetchResult.createSrrHasData(inboundMessageList);
			}
		}
		return result;
	}
}
